package test_framework;

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Email {

    private String host;
    private String user;
    private String pass;
    private String senderEmail;
    private String senderName;

    public Email(String host) {
        this.host = host;
    }

    public Email(String host, String user, String pass) {
        this.host = host;
        this.user = user;
        this.pass = pass;
    }

    public void setSender(String sendermail, String sendername) {
        this.senderEmail = sendermail;
        this.senderName = sendername;
    }

    public String getSenderName() {
        return this.senderName;
    }

    public void sendEmail(String Recipient, String subject, String content)
            throws MessagingException {
        Properties localProperties = new Properties();
        localProperties.put("mail.smtp.host", this.host);
        Session localSession;
        if (this.user != null) {
            MailAuthenticator localObject = new MailAuthenticator(this.user, this.pass);
            localProperties.put("mail.smtp.auth", "true");
            localSession = Session.getDefaultInstance(localProperties, (Authenticator) localObject);
        } else {
            localSession = Session.getDefaultInstance(localProperties);
        }
        Object localObject = new MimeMessage(localSession);
        ((Message) localObject).setFrom(new InternetAddress(this.senderEmail));
        ((Message) localObject).setRecipient(Message.RecipientType.TO, new InternetAddress(Recipient));
        ((Message) localObject).setSentDate(new Date());
        ((Message) localObject).setSubject(subject);
        ((Message) localObject).setContent(content, "text/plain");
        Transport.send((Message) localObject);
    }

    static class MailAuthenticator extends Authenticator {

        private final String user;
        private final String password;

        public MailAuthenticator(String user, String password) {
            this.user = user;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(this.user, this.password);
        }
    }
}